import { resolve } from "path";
import * as remote from "@electron/remote";
import { ColorType, ThemeConfig } from "./type";
import defaultConfig from "./defaultConfig";
import * as fs from "fs";
// // 初始化主题配置
// export const initThemeConfig = async () => {
//   const srcFilePath = resolve(app.global.path.resource, 'files/theme');
//   const themeConfig = getThemeConfig();
//   if (!themeConfig) return;
//   let imagesKey = Object.keys(themeConfig.images);
//   for (const element of imagesKey) {
//     const image = themeConfig.images[element];
//     if (image) themeConfig.images[element] = resolve(srcFilePath, image) + `?t=${Date.now()}`;
//   }
//   return themeConfig;
// };

// // 获取指定图片路径
// export const getThemeImage = async (key: string) => {
//   const srcFilePath = resolve(app.global.path.resource, 'files/theme');
//   const themeConfig = await getThemeConfig();
//   if (!themeConfig) return;
//   const image = themeConfig.images[key];
//   if (image) return resolve(srcFilePath, image) + `?t=${Date.now()}`;
// };

// // 获取主题配置
// export const getThemeConfig = async () => {
//   const srcFilePath = resolve(app.global.path.resource, 'files/theme');
//   const themeConfig = await localFile.readJsonFile(srcFilePath) as AppearanceSettingRuleForm;
//   return themeConfig;
// };

class ThemeConfigModel {
  // 主题相对路径
  themePath = "";
  // 图片路径
  imagesPath = "";
  // 图片文件夹名称
  imagesFolderName = "images";
  constructor() {
    let { themePath, imagesPath } = this.getPath();
    this.themePath = themePath;
    this.imagesPath = imagesPath;
  }
  getThemeConfig(): ThemeConfig {
    try {
      const themeConfig = this.readJsonFile(this.themePath) as ThemeConfig;
      return themeConfig;
    } catch (error) {
      // 防止配置读取失败
      console.log(error);
      return defaultConfig();
    }
  }
  // 获取配置路径
  getPath() {
    let themePath = "";
    // 不从globalPath 因为部分页面没有初始化globalPath
    if (process.env.NODE_ENV === "development") {
      themePath = resolve(remote.app.getAppPath(), "../.temp/theme");
    } else {
      themePath = resolve(remote.app.getPath("userData"), "../theme");
      // console.log('themePath1 =', themePath);
      if (!fs.existsSync(themePath)) {
        themePath = resolve(remote.app.getAppPath(), "../theme");
        // console.log('themePath2 =', themePath);
      }
    }
    const imagesPath = resolve(themePath, this.imagesFolderName);

    return { themePath, imagesPath };
  }
  // 直接获取图片
  getThemeImage(key: string) {
    const themeConfig = this.getThemeConfig();
    if (!themeConfig) return {};
    const image = themeConfig.images?.[key];
    if (!image) return { themeConfig };
    const imagePath = resolve(this.themePath, image);
    return { imagePath, themeConfig };
  }
  // 初始化主题配置
  initThemeConfig() {
    const themeConfig = this.getThemeConfig();
    let imagesKey = Object.keys(themeConfig.images);
    for (const element of imagesKey) {
      const image = themeConfig.images[element];
      if (image) themeConfig.images[element] = resolve(this.themePath, image) + `?t=${Date.now()}`;
    }

    this.setCssVar(ColorType.mdPrimaryColor, themeConfig.systemTheme.mdPrimaryColor);
    this.setCssVar(ColorType.mdSubColor1, themeConfig.systemTheme.activeSubColor1);
    this.setCssVar(ColorType.mdSubColor2, themeConfig.systemTheme.activeSubColor2);
    this.setCssVar(ColorType.mdSubColor3, themeConfig.systemTheme.activeSubColor3);
    if (themeConfig.systemTheme.mdPrimaryColor) {
      this.setCssVar(ColorType.mdPrimaryColor8, this.colorRgba(themeConfig.systemTheme.mdPrimaryColor, 0.75));
    }
    if (themeConfig.systemTheme.showSubColor1) {
      this.setCssVar(ColorType.mdSubColor15, this.colorRgba(themeConfig.systemTheme.showSubColor1, 0.5));
    }
    if (themeConfig.systemTheme.mdPrimaryColor) {
      this.setCssVar(ColorType.mdPrimaryColor4, this.colorRgba(themeConfig.systemTheme.mdPrimaryColor, 0.4));
    }
    this.createElLight(themeConfig.systemTheme.mdPrimaryColor);
    return themeConfig;
  }
  // 保存配置
  async saveThemeConfig(themeConfig: ThemeConfig): Promise<void> {
    await this.writeJsonFile<ThemeConfig>(themeConfigModel.themePath, themeConfig);
  }
  readJsonFile(filePath: string, fileName = "config.json") {
    const configPath = resolve(filePath, fileName);
    const config = fs.readFileSync(configPath, "utf-8");
    return JSON.parse(config);
  }

  // 写入json文件内容
  async writeJsonFile<T>(filePath: string, data: T, fileName = "config.json") {
    const configPath = resolve(filePath, fileName);
    await fs.promises.writeFile(configPath, JSON.stringify(data, null, 2), "utf-8");
  }
  // 返回图片url路径
  async createURL(filePath: string) {
    try {
      await fs.promises.access(filePath);
      let data = await fs.promises.readFile(filePath);
      const blob = new Blob([data]);
      return URL.createObjectURL(blob);
    } catch (error) {
      return "";
    }
  }
  setCssVar(varName: string, color: string, targetElement: HTMLElement | null = document.documentElement) {
    // 确保变量名以 "--" 开头
    const normalizedVarName = varName.startsWith("--") ? varName : `--${varName}`;
    // 初始化读取当前值
    if (targetElement) {
      targetElement.style.setProperty(normalizedVarName, color);
    }
  }
  /**
   * JS颜色十六进制转换为rgb或rgba,返回的格式为 rgba（255，255，255，0.5）字符串
   * sHex为传入的十六进制的色值
   * alpha为rgba的透明度
   */
  colorRgba(sHex: string, alpha: number) {
    let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    /* 16进制颜色转为RGB格式 */
    let sColor = sHex.toLowerCase();
    if (sColor && reg.test(sColor)) {
      if (sColor.length === 4) {
        let sColorNew = "#";
        for (let i = 1; i < 4; i += 1) {
          sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
        }
        sColor = sColorNew;
      }
      // 处理六位的颜色值
      let sColorChange: number[] = [];
      for (let i = 1; i < 7; i += 2) {
        sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
      }
      return "rgba(" + sColorChange.join(",") + "," + alpha + ")";
    } else {
      return sColor;
    }
  }
  // 生成el-light
  createElLight(color: string) {
    const mix = (color1: string, color2: string, weight: number) => {
      weight = Math.max(Math.min(Number(weight), 1), 0);
      const r1 = parseInt(color1.substring(1, 3), 16);
      const g1 = parseInt(color1.substring(3, 5), 16);
      const b1 = parseInt(color1.substring(5, 7), 16);
      const r2 = parseInt(color2.substring(1, 3), 16);
      const g2 = parseInt(color2.substring(3, 5), 16);
      const b2 = parseInt(color2.substring(5, 7), 16);
      const r = Math.round(r1 * (1 - weight) + r2 * weight);
      const g = Math.round(g1 * (1 - weight) + g2 * weight);
      const b = Math.round(b1 * (1 - weight) + b2 * weight);
      const _r = ("0" + (r || 0).toString(16)).slice(-2);
      const _g = ("0" + (g || 0).toString(16)).slice(-2);
      const _b = ("0" + (b || 0).toString(16)).slice(-2);
      return "#" + _r + _g + _b;
    };

    const node = document.documentElement;
    // 前缀
    const pre = ColorType.mdPrimaryColor;
    // 源码中的$color-white
    const mixWhite = "#ffffff";
    node.style.setProperty(pre, color);
    for (let i = 1; i < 10; i += 1) {
      this.setCssVar(`${pre}-light-${i}`, mix(color, mixWhite, i * 0.1));
    }
  }
  // 保存到 userData 里面
  saveUserData() {
    const writePath = resolve(remote.app.getPath("userData"), "./theme");
    if (!fs.existsSync(writePath)) {
      if (process.env.NODE_ENV === "development") {
        copyFolderSync(resolve(remote.app.getAppPath(), "../theme/Design"), resolve(remote.app.getPath("userData"), "./theme"));
      } else {
        // console.log('==', resolve(remote.app.getAppPath(), './theme'), resolve(remote.app.getPath('userData'), './theme'));
        const theme = resolve(remote.app.getPath("userData"), "./theme");
        if (!fs.existsSync(theme)) {
          fs.mkdirSync(theme);
        }
        const targetDir = resolve(remote.app.getPath("userData"), "./theme");
        if (!fs.existsSync(targetDir)) {
          fs.mkdirSync(targetDir);
        }
        copyFolderSync(resolve(remote.app.getAppPath(), "../theme"), targetDir);
      }
    }
    let { themePath, imagesPath } = this.getPath();
    this.themePath = themePath;
    this.imagesPath = imagesPath;
  }
  reset() {
    if (process.env.NODE_ENV === "development") {
      console.log(remote.app.getPath("userData"));
      const targetDir = resolve(remote.app.getPath("userData"), "./theme");
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir);
      }
      copyFolderSync(resolve(remote.app.getAppPath(), "../theme/Design"), targetDir);
      let { themePath, imagesPath } = this.getPath();
      this.themePath = themePath;
      this.imagesPath = imagesPath;
    } else {
      // console.log('reset =', resolve(remote.app.getAppPath(), '../theme/Design'), resolve(remote.app.getPath('userData'), './theme'));
      copyFolderSync(resolve(remote.app.getAppPath(), "../theme"), resolve(remote.app.getPath("userData"), "./theme"));

      let { themePath, imagesPath } = this.getPath();
      this.themePath = themePath;
      this.imagesPath = imagesPath;
    }
  }
}
const mkDir = dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  } else {
    fs.rmSync(dir, { recursive: true }); //  目录不为空，则先删除该目录，重新复制文件，防止文件内容有更新
    fs.mkdirSync(dir);
  }
};
function copyFolderSync(source, target) {
  // 复制目录下的文件到目标目录下
  const dirs = fs.readdirSync(source, { encoding: "utf8", withFileTypes: true });
  // console.log('dirs =', dirs);
  dirs.forEach(dir => {
    const originPath = resolve(source, dir.name);
    const copyPath = resolve(target, dir.name);
    if (dir.isDirectory()) {
      // 判断是否是文件夹，是的话递归进行
      mkDir(copyPath);
      copyFolderSync(originPath, copyPath);
    } else {
      fs.copyFileSync(originPath, copyPath);
    }
  });
}

export const themeConfigModel = new ThemeConfigModel();
